#pragma once
#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


#define Creater 1
#define User    2
#define Read O_RDONLY
#define Write O_WRONLY
#define BaseSize 4096
const std::string gPathname = "./myfifo";
class NamedPipe
{
private:
    bool OpenNamedPipe(int mode)
    {
        _fd = open(_pathname.c_str(), mode);
        if (_fd == -1)
            return false;
        return true;
    }
public:
    NamedPipe(std::string name, int who, int fd = -1)
        :_pathname(name), _who(who), _fd(fd)
    {
        if (_who == Creater)
        {
            // 创建管道
            int ret = mkfifo(_pathname.c_str(), 0666);
            if (ret != 0 )
            {
                perror("mkfifo");
            }
            std::cout << "creater create named pipe sucess" << std::endl;
        }
    }
    ~NamedPipe()
    {
        // 删除管道文件
        if (_who == Creater)
        {
            int ret = unlink(_pathname.c_str());
            if (ret != 0)
            {
                perror("unlink");
            }
            std::cout << "creater remove named pipe sucess" << std::endl;
        }
        // 关闭文件fd
        if(_fd != -1) close(_fd);
    }

    bool OpenForRead()
    {
        return OpenNamedPipe(Read);
    }

    bool OpenForWrite()
    {
        return OpenNamedPipe(Write);
    }

    int ReadNamedPipe(std::string* out)
    {
        char buffer[BaseSize];
        int n = read(_fd, &buffer, sizeof(buffer));
        if (n > 0)
        {
            // 读取成功
            buffer[n] = 0;
            *out = buffer;
        }
        return n;
    }

    int WriteNamedPipe(const std::string& in)
    {
        return write(_fd, in.c_str(), in.size());
    }

private:
    std::string _pathname; // 命名管道的名字
    int _who; // 打开管道者的身份
    int _fd; // 文件fd
};